package com.bulletelc.apollopre.module.display.product.details.introduce;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.OrderConfirmBean;
import com.bulletelc.apollopre.entity.ProductAssociate;
import com.bulletelc.apollopre.entity.ProductBannerImg;
import com.bulletelc.apollopre.entity.ProductDetailAll;
import com.bulletelc.apollopre.entity.ProductEav;
import com.bulletelc.apollopre.entity.ProductEavValueBean;
import com.bulletelc.apollopre.framework.MVPBaseFragment;
import com.bulletelc.apollopre.manager.imageload.ImageLoaderManager;
import com.bulletelc.apollopre.module.deal.clearing.ClearingActivity;
import com.bulletelc.apollopre.module.display.product.details.ProductDetailsActivity;
import com.bulletelc.apollopre.module.user.LoginMainActivity;
import com.bulletelc.apollopre.module.web.WebPageActivity;
import com.bulletelc.apollopre.utils.BannerImageLoader;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.CustomListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * author: lhl
 * date  : 2018/01/15
 * desc  : 商品详情界面---商品
 */

public class IntroduceFragment extends MVPBaseFragment<IntroduceContract.View, IntroducePresenter> implements IntroduceContract.View,
        View.OnClickListener, ChooseAdapter.OnItemClickListener {

    // views
    private Banner banner;
    private WebView webView; // 商品介绍
    private Button btnExplain; // 安装费活动说明
    private TextView tvInstallFee, tvProductName, tvPrice, tvChoose, tvSold;
    private LinearLayout llChoose, llShare;
    private Dialog chooseDialog; // 货品选择Dialog
    private List<TextView> textViews; // 产品的具体货品名字集
    private TextView tvOrderNum; // Dialog的显示购买的数量
    private ImageButton iBtnAdd, iBtnMinus, iBtnClose; // Dialog的增减数量，关闭按钮
    private Button btnAddCart; // Dialog的加入购物车
    private Button btnBuyNow;  // Dialog的立即狗迷
    private LinearLayout llSku; // Dialog货品名字
    private ListView lv; // Dialog货品ListView
    private TextView tvPrice1; // Dialog的价格
    private ImageView ivIcon; // Dialog的图片
    private ChooseAdapter chooseAdapter;
    private RelativeLayout rlInstallPanel; // 安装费显示ViewGroup
    private LinearLayout llAssociate; // 关联产品
    private CustomListView lvAssociate;

    // data 产品
    private String productId;
    private ProductDetailAll productDetailAll;
    private List<ProductEav> productEavs; // 选项卡
    private List<ProductEavValueBean> eavValueBeans; // 选项卡中的value
    private int num = 1; // 购买的数量
    private int productSkuId; // 商品规格ID,
    private String skuPrice; // sku的价格
    private String productSkuName = "";
    private int release; // 1上架 2下架
    private int install; // 1安装 0不装
    // data 关联产品
    private List<ProductAssociate> productAssociates;
    private AssociateAdapter adapter;
    private TextView tvTotalAssociatePrice;
    private double totalAssociatePrice = 0;//记录关联产品总价
    private List<String> imageUrls; // 轮播图的图片地址集合

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    @Override
    public int getLayoutRes() {
        return R.layout.product_introduce_fragment;
    }

    @Override
    public void assignViews() {
        banner = findView(R.id.banner);
        btnExplain = findView(R.id.btnExplain);
        llAssociate = findView(R.id.llAssociate);
        tvTotalAssociatePrice = findView(R.id.tvTotalAssociatePrice);
        tvProductName = findView(R.id.tvProductName);
        tvPrice = findView(R.id.tvPrice);
        llChoose = findView(R.id.llChoose);
        tvChoose = findView(R.id.tvChoose);
        llShare = findView(R.id.llShare);
        tvSold = findView(R.id.tvSold);
        tvInstallFee = findView(R.id.tvInstallFee);
        lvAssociate = findView(R.id.lvAssociate);
        webView = findView(R.id.webView);
        rlInstallPanel = findView(R.id.rlInstallPanel);
    }

    @Override
    public void setListener() {
        llChoose.setOnClickListener(this);
        llShare.setOnClickListener(this);
        btnExplain.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // 拿到主体商品ID
        productId = ((ProductDetailsActivity) baseActivity).getProductId();
        productEavs = new ArrayList<>();
        productAssociates = new ArrayList<>();
        textViews = new ArrayList<>();
        initBanner();
        initWebView();
        presenter.getProductDetails(productId);

    }

    @Override
    protected IntroducePresenter createPresenter() {
        return new IntroducePresenter();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llChoose:
                showChooseDialog();
                break;

            case R.id.btnExplain:
                bargainExplain();
                break;

            case R.id.llShare:
                if (productDetailAll != null) {
                    ProductDetailsActivity.showShareDialog.showShareDialog();
                } else {
                    Toast.makeText(getContext(), "数据加载中，请稍后再试", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.btnToAddress: //地址dialog的button
                Toast.makeText(baseActivity, "跳转到地址界面", Toast.LENGTH_SHORT).show();
                break;

            case R.id.iBtnMinus: //减少数量
                if (num > 1) {
                    num--;
                    tvOrderNum.setText(String.valueOf(num));
                    ((ProductDetailsActivity) baseActivity).setNum(num);
                    tvChoose.setText(productSkuName + "/数量:" + num);
                }
                break;

            case R.id.iBtnAdd: //增加数量
                num++;
                tvOrderNum.setText(String.valueOf(num));
                ((ProductDetailsActivity) baseActivity).setNum(num);
                tvChoose.setText(productSkuName + "/数量:" + num);
                break;

            case R.id.btnAddCart://加入购物车
                if (release == 1) {
                    addCart();
                } else if (release == 0) {
                    ToastUtil.showLongToast(baseActivity, "该商品已下架");
                }
                break;

            case R.id.btnBuyNow: //立即购买
                if (release == 1) {
                    buyNow();
                } else if (release == 0) {
                    ToastUtil.showLongToast(baseActivity, "该商品已下架");
                }
                break;

            case R.id.iBtnClose:
                chooseDialog.dismiss();
                break;

        }
    }

    @Override
    public void onItemClick(int groupPosition, int childPosition, boolean isChecked) {
        if (isChecked) {
            for (int i = 0, size = productEavs.get(groupPosition).getProductEavValueBeans().size(); i < size; i++) {
                productEavs.get(groupPosition).getProductEavValueBeans().get(i).setChecked(false);
            }
            productEavs.get(groupPosition).getProductEavValueBeans().get(childPosition).setChecked(isChecked);
            chooseAdapter.notifyDataSetChanged();

            String attrParams = "";
            for (int i = 0, size = productEavs.size(); i < size; i++) {
                attrParams += productEavs.get(i).getAttribute_code() + ":";
                for (int j = 0, sizeJ = productEavs.get(i).getProductEavValueBeans().size(); j < sizeJ; j++) {
                    if (productEavs.get(i).getProductEavValueBeans().get(j).isChecked()) {
                        attrParams += productEavs.get(i).getProductEavValueBeans().get(j).getId();
                        if (i < size - 1) {
                            attrParams += "/";
                        }

                    }
                }
            }

            productSkuId = 0;
            for (int i = 0, size = productDetailAll.getProduct_sku_list().size(); i < size; i++) {
                if (productDetailAll.getProduct_sku_list().get(i).getAttr_params().equals(attrParams)) {
                    productSkuId = productDetailAll.getProduct_sku_list().get(i).getId();
                    String price = "¥" + MyUtil.format2(productDetailAll.getProduct_sku_list().get(i).getPrice());
                    tvPrice1.setText(price);
                    tvPrice.setText(price);
                    productSkuName = productDetailAll.getProduct_sku_list().get(i).getName();
                    tvChoose.setText(productSkuName + "/数量:" + num);
                    double installFee = productDetailAll.getProduct_sku_list().get(i).getInstall_fee();
                    if (installFee == 0) {
                        rlInstallPanel.setVisibility(View.GONE); // 隐藏安装费
                    } else {
                        rlInstallPanel.setVisibility(View.VISIBLE);
                        tvInstallFee.setText(MyUtil.format2(installFee)); // 设置安装费
                    }
                    setProductSkuName(productSkuName); // 设置Dialog ProductSkuName
                    ((ProductDetailsActivity) baseActivity).setProductSkuId(productSkuId); // 更新Activity ProductId
                    ((ProductDetailsActivity) baseActivity).setShowDialog(false);

                    return;
                }
            }

        }
    }

    @Override
    public void onSuccess(ProductDetailAll productDetailAll) {
        if (null != productDetailAll) {
            this.productDetailAll = productDetailAll;
            this.productSkuName = productDetailAll.getProduct_sku_list().get(0).getName(); // 默认第一
            this.skuPrice = MyUtil.format2(productDetailAll.getProduct_sku_list().get(0).getPrice());
            this.release = productDetailAll.getIs_released(); // 设置是否上架
            this.install = productDetailAll.getIs_install(); // 设置是否安装
            this.productAssociates.addAll(productDetailAll.getAssociated_products()); // 设置关联产品
            ((ProductDetailsActivity) baseActivity).update(productDetailAll); // 更新Activity
            updateBanner(); // 更新banner
            updateSkuData(); // 更新货品
            updateIntroduce(); // 更新Fragment
            updateAssociateListView(); // 更新关联产品
            webView.loadUrl(NetWorkPath.WEB_VIEW_PRODUCT_DETAIL + "?id=" + productDetailAll.getId()); //加载WebView
        }

    }

    @Override
    public void onFail(String fail) {
        ToastUtil.showLongToast(getActivity(), fail);
    }

    @Override
    public void onError(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccessAddCart() {
        Toast.makeText(baseActivity, "添加成功", Toast.LENGTH_SHORT).show();
        String chooseStr = "";
        for (int i = 0, size = llSku.getChildCount(); i < size; i++) {
            chooseStr += ((TextView) llSku.getChildAt(i)).getText().toString();
        }
        productSkuName = chooseStr;
        tvChoose.setText(chooseStr + "/数量:" + num);
        chooseDialog.dismiss();
    }

    @Override
    public void onFailAddCart(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorAddCart(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccessBuyNow(OrderConfirmBean confirmBean) {
        if (confirmBean != null) {
            Intent intent = new Intent(baseActivity, ClearingActivity.class);
            intent.putExtra(IntentCode.EXTRA_KEY_CONFIRM_ORDER_DATA, confirmBean);
            startActivity(intent);
        } else {
            Toast.makeText(baseActivity, "数据有误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailBuyNow(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorBuyNow(String error) {
        Toast.makeText(baseActivity, R.string.network_msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 加入购物车
     */
    private void addCart() {

        String token = MyApplication.getToken();
        if (token != null && token.length() > 0) {
            String json = getJson();

            if (json != null) {
                if (productSkuId != 0) {
                    presenter.addCart(json, token);
                } else {
                    Toast.makeText(baseActivity, getString(R.string.toast_product_sku_unselected), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(baseActivity, "请求参数的格式错误", Toast.LENGTH_SHORT).show();
            }
        } else {
            Intent intent = new Intent(baseActivity, LoginMainActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 获取添加到购物车所需要的json参数
     *
     * @return
     */
    private String getJson() {
        String json = null;
        JSONObject object = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONObject subObject = new JSONObject();
        try {
            subObject.put("buy_num", num); // 默认1
            //subObject.put("cart_item_id",""); // 非必传
            subObject.put("product_id", productId); // 商品ID
            subObject.put("product_sku_id", productSkuId); // 商品规格id，默认第一个
            subObject.put("supplier_id", productDetailAll.getSupplier_id()); // 供应商id
            subObject.put("is_install", install); // 是否安装
            jsonArray.put(0, subObject);
            object.put("cart_item", jsonArray);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 立即购买
     */
    private void buyNow() {
        String token = MyApplication.getToken();
        if (token != null && token.length() > 0) {
            String json = getJsonBuyNow();
            if (json != null) {
                if (productSkuId != 0) {
                    presenter.buyNow(json, token);
                } else {
                    Toast.makeText(baseActivity, getString(R.string.toast_product_sku_unselected), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(baseActivity, "请求参数的格式错误", Toast.LENGTH_SHORT).show();
            }
        } else {
            Intent intent = new Intent(baseActivity, LoginMainActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 立即购买所需要的json参数
     *
     * @return
     */
    private String getJsonBuyNow() {
        String json = null;
        JSONObject object = new JSONObject();
        JSONObject subObj = new JSONObject();
        try {
            subObj.put("buy_num", String.valueOf(num)); // 购买数量
            subObj.put("product_id", productId); // 商品ID
            //subObj.put("cart_item_id", ""); // 非必传
            subObj.put("product_sku_id", productSkuId); // 商品规格id
            subObj.put("supplier_id", productDetailAll.getSupplier_id()); // 供应商id
            subObj.put("is_install", install); // 是否安装
            object.put("product", subObj);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //LogUtil.i(json);
        return json;
    }

    /**
     * 初始化banner
     */
    private void initBanner() {
        imageUrls = new ArrayList<>();
        //设置图片集合
        banner.setImages(imageUrls);
        //设置图片加载器
        banner.setImageLoader(new BannerImageLoader());

        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置标题集合（当banner样式有显示title时）
        //banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.start();
    }

    /**
     * 初始化WebView
     */
    private void initWebView() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//支持js
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不缓存
        webView.setWebViewClient(new WebViewClient());
    }

    /**
     * 显示选择的dialog
     */
    public void showChooseDialog() {
        if (productDetailAll != null) {
            if (chooseDialog == null) {
                View view = LayoutInflater.from(baseActivity).inflate(R.layout.dialog_cart_choose, null);
                chooseDialog = new Dialog(baseActivity, R.style.common_dialog);
                chooseDialog.setContentView(view);

                //关联控件
                ivIcon = view.findViewById(R.id.ivProductIcon);
                tvPrice1 = view.findViewById(R.id.tvPrice);
                lv = view.findViewById(R.id.lvEav);
                llSku = view.findViewById(R.id.llSku);
                iBtnMinus = view.findViewById(R.id.iBtnMinus);
                tvOrderNum = view.findViewById(R.id.tvOrderNum);
                iBtnAdd = view.findViewById(R.id.iBtnAdd);
                btnAddCart = view.findViewById(R.id.btnAddCart);
                btnBuyNow = view.findViewById(R.id.btnBuyNow);
                iBtnClose = view.findViewById(R.id.iBtnClose);

                iBtnMinus.setOnClickListener(this);
                iBtnAdd.setOnClickListener(this);
                btnAddCart.setOnClickListener(this);
                btnBuyNow.setOnClickListener(this);
                iBtnClose.setOnClickListener(this);

                chooseAdapter = new ChooseAdapter(baseActivity, productEavs);
                chooseAdapter.setOnItemClickListener(this);
                lv.setAdapter(chooseAdapter);

                // 设置第一个
                setProductSkuName(productSkuName);
                tvPrice1.setText("¥" + skuPrice);
                ImageLoaderManager.getInstance().loadImage(ImageLoaderManager.getDefaultOptions(ivIcon, productDetailAll.getProduct_sku_list().get(0).getLogo_url()));

                Window window = chooseDialog.getWindow();
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams params = window.getAttributes();
                params.width = WindowManager.LayoutParams.MATCH_PARENT;
                params.height = WindowManager.LayoutParams.WRAP_CONTENT;
                params.gravity = Gravity.BOTTOM;
                window.setAttributes(params);

                chooseDialog.show();
            } else {
                chooseDialog.show();
            }
        } else {
            Toast.makeText(baseActivity, "数据加载中,请稍后再试", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 更新Banner,并赋值
     */
    public void updateBanner() {
        List<String> bannersUpdate = new ArrayList<>();
        List<ProductBannerImg> bannerImgList = productDetailAll.getBanner_img_list();
        for (int i = 0, size = bannerImgList.size(); i < size; i++) {
            bannersUpdate.add(bannerImgList.get(i).getImg_url());
        }
        banner.update(bannersUpdate);
    }

    /**
     * 更新Introduce界面数据
     */
    public void updateIntroduce() {

        // 设置Fragment第一个货品信息
        tvProductName.setText(productDetailAll.getName());
        tvPrice.setText("¥" + skuPrice);
        tvSold.setText("已售:" + productDetailAll.getSold());
        tvChoose.setText(productSkuName + "/数量:" + num);

        if (productDetailAll.getIs_show_install() == 0) {
            // 不显示安装费
            rlInstallPanel.setVisibility(View.GONE);
        } else {
            // 默认拿对应的第一个货品安装费展示
            tvInstallFee.setText("¥" + MyUtil.format2(productDetailAll.getProduct_sku_list().get(0).getInstall_fee()));
        }

    }

    /**
     * 更新SKU选择所需数据
     */
    public void updateSkuData() {
        //准备选项卡数据:
        productEavs = productDetailAll.getProduct_eav();
        for (int i = 0, size = productEavs.size(); i < size; i++) {
            String value = productEavs.get(i).getValue();
            if (value != null && !"".equals(value)) {
                if (!value.contains("[")) {
                    Gson gson = new Gson();
                    Map<String, String> maps = gson.fromJson(value, new TypeToken<Map<String, String>>() {
                    }.getType());
                    List<ProductEavValueBean> eavValueBeans = new ArrayList<>();
                    for (Map.Entry<String, String> entry : maps.entrySet()) {
                        ProductEavValueBean eavValueBean = new ProductEavValueBean();
                        eavValueBean.setId(entry.getKey());
                        eavValueBean.setName(entry.getValue());
                        eavValueBeans.add(eavValueBean);
                    }
                    productEavs.get(i).setProductEavValueBeans(eavValueBeans);
                }
            }
        }

        // 过滤掉value没有值的item
        List<ProductEav> productEavs1 = new ArrayList<>();
        for (int i = 0, size = productEavs.size(); i < size; i++) {
            if (productEavs.get(i).getProductEavValueBeans() != null && productEavs.get(i).getProductEavValueBeans().size() > 0) {
                ProductEav productEav = productEavs.get(i);
                productEav.getProductEavValueBeans().get(0).setChecked(true);
                productEavs1.add(productEav);
            }
        }
        productEavs.clear();
        productEavs.addAll(productEavs1);

        // 设置skuId
        productSkuId = productDetailAll.getProduct_sku_list().get(0).getId();
        ((ProductDetailsActivity) baseActivity).setProductSkuId(productSkuId);
    }

    /**
     * 初始化关联产品需求
     */
    private void updateAssociateListView() {
        if (productAssociates.size() > 0) {
            llAssociate.setVisibility(View.VISIBLE);
            adapter = new AssociateAdapter(baseActivity, productAssociates);
            lvAssociate.setAdapter(adapter);
            adapter.setOnItemCheckChangeListener(new AssociateAdapter.OnItemCheckChangeListener() {
                @Override
                public void checked(double price) {
                    totalAssociatePrice += price;
                    tvTotalAssociatePrice.setText("参考价格：¥" + MyUtil.format2(totalAssociatePrice));
                }
            });
            for (ProductAssociate pa : productAssociates) {
                totalAssociatePrice += Double.parseDouble(pa.getSales_price());
            }
            tvTotalAssociatePrice.setText("参考价格：¥" + MyUtil.format2(totalAssociatePrice));
        }
    }

    /**
     * 砍价说明
     */
    private void bargainExplain() {
        Intent intent = new Intent(baseActivity, WebPageActivity.class);
        intent.putExtra(IntentCode.EXTRA_WEB_PAGE_FLAG, GlobalConfig.WEB_PAGE_FOR_CUT_PRICE_REGULAR);
        intent.putExtra(IntentCode.EXTRA_KEY_URL, NetWorkPath.GET_BARGAIN_EXPLAIN);
        startActivity(intent);
    }

    /**
     * 设置货品选择框货品名字
     * @param productSkuName
     */
    private void setProductSkuName(String productSkuName) {
        llSku.removeAllViewsInLayout();
        TextView tv = new TextView(baseActivity);
        tv.setText(productSkuName);
        textViews.add(tv);
        llSku.addView(tv);
    }

}
